<template>
  <div class="editor-select-goods-btn">
    <div class="editor-select-goods-count" v-if="data && data.length">
      已选择{{ data.length }}个
    </div>
    <div class="editor-select-goods-btn-text" @click="selectClick">
      {{ text }}
    </div>
  </div>
  <storeSelectGoodsModal
    v-if="modalStatus"
    ref="storeSelectGoodsModalRef"
    @change="selectedChange"
    v-model:ids="ids"
    v-model:data="data"
  ></storeSelectGoodsModal>
</template>
      <script lang="ts">
export default {
  name: "storeDiyFormSelectGoodsBtn",
};
</script>
  
  <script  lang="ts" setup >
import { ref, getCurrentInstance, watch, nextTick } from "vue";
import storeSelectGoodsModal from "@/components/select-modal/goods/index.vue";
const props = withDefaults(
  defineProps<{
    text?: string;
    ids: Array<string | number>;
    data: any;
  }>(),
  {
    text: "选择商品",
    ids: () => {
      return [];
    },
    data: [],
  }
);
const {
  proxy,
  proxy: { $utils },
} = getCurrentInstance() as any;

const emit = defineEmits(["update:ids", "update:data", "change"]);

const storeSelectGoodsModalRef = ref<HTMLElement>();

const modalStatus = ref<boolean>(false);

const selectClick = () => {
  modalStatus.value = true;
  nextTick(() => {
    proxy?.$refs["storeSelectGoodsModalRef"]?.open(props.ids, props.data);
  });
};

const selectedChange = (obj: {
  ids: number[] | string[] | number | string;
  data: any;
}) => {
  selectData.value = obj.data
  selectIds.value = obj.ids
  modalStatus.value = false;
  emit("change", obj);
  emit("update:data", obj.data);
  emit("update:ids", obj.ids);
};

const selectData = ref<any>(props.data);
const selectIds = ref<any>(props.ids);

const del = (id: number | string) => {
  var index = $utils.arrayFilterMultiple(selectData.value, "id", id);
  if (index !== -1) {
    selectData.value.splice(index, 1);
  }
  var idIdx = $utils.arrayFilterMultiple(selectIds.value, false, id);
  if (idIdx !== -1) {
    selectIds.value.splice(idIdx, 1);
  }
  emit("change", {
    ids: selectIds.value,
    data: selectData.value,
  });
  emit("update:data", selectData.value);
  emit("update:ids", selectIds.value);
};

defineExpose({ del });
</script>
  
  
  <style scoped>
.editor-select-goods-btn {
  display: flex;
  justify-content: flex-end;
  height: 40px;
  line-height: 40px;
}
.editor-select-goods-btn-text {
  cursor: pointer;
  background: #f0f0f0;
  color: #000;
  border: 1px solid #f0f0f0;
  margin: 5px 0;
  height: 30px;
  line-height: 30px;
  padding: 0 10px;
  border-radius: 2px;
  font-size: 12px;
  white-space: nowrap;
  user-select: none;
}
.editor-select-goods-btn-text:hover {
  background: var(--el-color-primary-light-9);
  border: 1px solid var(--base-default);
  color: var(--base-default);
}

.editor-select-goods-count {
  font-size: 12px;
  color: var(--base-default);
  margin-right: 10px;
}
</style>